package com.lxg.springboot.config;

import com.lxg.springboot.entity.Resource;
import com.lxg.springboot.entity.Role;
import com.lxg.springboot.entity.User;
import com.lxg.springboot.mapper.ResourceRepository;
import com.lxg.springboot.service.UserRoleService;
import com.lxg.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.*;

public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private ResourceRepository resourceRepository;

    /**
     * 根据用户名获取登录用户信息
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByUsername(username);

        if (user == null) {
            throw new UsernameNotFoundException("用户名：" + username + "不存在！");
        }
        Collection<SimpleGrantedAuthority> collection = new HashSet<SimpleGrantedAuthority>();
        Iterator<Role> iterator = user.getList().iterator();
        while (iterator.hasNext()) {
            collection.add(new SimpleGrantedAuthority(iterator.next().getRole_name()));
        }

//        List<Resource> permissions = resourceRepository.findResByUserId(user.getId());
//        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
//        for (Resource permission : permissions) {
//            if (permission != null && permission.getResName() != null) {
//
//                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getResName());
//                //1：此处将权限信息添加到 GrantedAuthority 对象中，在后面进行全权限验证时会使用GrantedAuthority 对象。
//                grantedAuthorities.add(grantedAuthority);
//            }
//        }
        return new org.springframework.security.core.userdetails.User(username, user.getPassword(), collection);
    }
}
